/**
 * 表格组件相关帮助函数
 */
import { objectInArray } from '../../arrays';
import { getProp } from '../../objects/helpers';

/**
 * 切换行的选中状态
 * @param {Record<string, any>} row - 要切换的行
 * @param {Record<string, any>[]} selectedRows - 当前选中的行数组
 * @param {string | ((row: Record<string, any>) => PropertyKey) | undefined} rowKey - 行键配置
 * @param {boolean} [selected] - 指定选中状态，不指定则切换当前状态
 * @returns {Record<string, any>[]} 切换后的选中行数组
 *
 * @example
 * // 切换行的选中状态（添加到已选中数组）
 * const selectedRows = [];
 * const newSelected1 = toggleRowSelection({ id: 1, name: '张三' }, selectedRows, 'id');
 * // newSelected1 现在包含 [{ id: 1, name: '张三' }]
 * 
 * // 切换行的选中状态（从已选中数组中移除）
 * const newSelected2 = toggleRowSelection({ id: 1, name: '张三' }, newSelected1, 'id');
 * // newSelected2 现在为空数组 []
 * 
 * // 强制设置选中状态
 * const newSelected3 = toggleRowSelection({ id: 2, name: '李四' }, [], 'id', true);
 * // newSelected3 现在包含 [{ id: 2, name: '李四' }]
 * 
 * // 使用函数rowKey
 * const newSelected4 = toggleRowSelection(
 *   { id: 3, name: '王五' },
 *   [],
 *   row => row.id
 * );
 * // newSelected4 现在包含 [{ id: 3, name: '王五' }]
 */
export function toggleRowSelection(
  row: Record<string, any>,
  selectedRows: Record<string, any>[],
  rowKey?: string | ((row: Record<string, any>) => PropertyKey),
  selected?: boolean
): Record<string, any>[] {
  const isSelected = objectInArray(
    row,
    selectedRows,
    rowKey
  );
  const newSelected = selected !== undefined ? selected : !isSelected;
  const newSelectedRows = [...selectedRows];

  if (newSelected && !isSelected) {
    newSelectedRows.push(row);
  } else if (!newSelected && isSelected) {
    return newSelectedRows.filter(item => {
      if (rowKey) {
        if (typeof rowKey === 'function') {
          return rowKey(item) !== rowKey(row);
        }
        return getProp(item, rowKey as string) !== getProp(row, rowKey as string);
      }
      return item !== row;
    });
  }

  return newSelectedRows;
}